<template>
  <div class="factory-reset-config">
    <a-form layout="vertical">
      <a-card title="出厂设置" :bordered="false">
        <a-alert
          message="警告"
          description="出厂重置将清除所有配置信息，恢复到设备出厂状态。此操作不可逆转，请谨慎操作。"
          type="warning"
          show-icon
          style="margin-bottom: 16px"
        />

        <a-form-item label="重置选项">
          <a-checkbox-group v-model:value="resetOptions">
            <a-checkbox value="preserve_network">保留网络配置</a-checkbox>
            <a-checkbox value="restart_system" :checked="true">重置后自动重启系统</a-checkbox>
          </a-checkbox-group>
          <div style="color: #999; font-size: 12px; margin-top: 8px">
            建议保留网络配置以避免设备失联
          </div>
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button 
              type="primary" 
              danger 
              size="large"
              :loading="isResetting"
              @click="showConfirmModal"
            >
              执行出厂重置
            </a-button>
            <a-button 
              type="default" 
              size="large"
              :loading="isRestarting"
              @click="showRestartConfirmModal"
            >
              系统重启
            </a-button>
          </a-space>
        </a-form-item>
      </a-card>
    </a-form>

    <!-- 确认对话框 -->
    <a-modal
      v-model:visible="confirmModalVisible"
      title="确认出厂重置"
      :closable="false"
      :maskClosable="false"
    >
      <div>
        <a-alert
          message="最后确认"
          description="此操作将永久删除所有配置，您确定要继续吗？"
          type="error"
          show-icon
        />
        
        <div style="margin-top: 16px">
          <p><strong>重置选项：</strong></p>
          <ul>
            <li v-if="resetOptions.includes('preserve_network')">✓ 保留网络配置</li>
            <li v-else>✗ 清除网络配置</li>
            <li v-if="resetOptions.includes('restart_system')">✓ 重置后自动重启</li>
            <li v-else>✗ 重置后不重启</li>
          </ul>
        </div>

        <div style="margin-top: 16px">
          <a-input
            v-model:value="confirmText"
            placeholder="请输入 'RESET' 确认执行重置"
            style="width: 100%"
          />
        </div>
      </div>

      <template #footer>
        <a-button @click="confirmModalVisible = false" :disabled="isResetting">
          取消
        </a-button>
        <a-button 
          type="primary" 
          danger 
          :loading="isResetting"
          :disabled="confirmText !== 'RESET'"
          @click="performReset"
        >
          确认重置
        </a-button>
      </template>
    </a-modal>

    <!-- 重启确认对话框 -->
    <a-modal
      v-model:visible="restartConfirmVisible"
      title="确认系统重启"
      :closable="false"
      :maskClosable="false"
    >
      <div>
        <a-alert
          message="系统重启确认"
          description="确定要重启系统吗？重启后需要重新连接设备。"
          type="warning"
          show-icon
        />
        
        <div style="margin-top: 16px">
          <a-form-item label="重启延时（秒）">
            <a-input-number
              v-model:value="restartDelay"
              :min="0"
              :max="60"
              style="width: 120px"
            />
            <span style="margin-left: 8px; color: #666">建议设置3-5秒延时</span>
          </a-form-item>
        </div>
      </div>

      <template #footer>
        <a-button @click="restartConfirmVisible = false" :disabled="isRestarting">
          取消
        </a-button>
        <a-button 
          type="primary"
          :loading="isRestarting"
          @click="performRestart"
        >
          确认重启
        </a-button>
      </template>
    </a-modal>

    <!-- 重置进度对话框 -->
    <a-modal
      v-model:visible="resetProgressVisible"
      title="正在执行出厂重置"
      :closable="false"
      :maskClosable="false"
      :footer="null"
    >
      <div class="reset-progress">
        <a-spin size="large">
          <div class="reset-message">
            {{ resetMessage }}
          </div>
        </a-spin>
        
        <div v-if="rebootCountdown > 0" class="reboot-countdown">
          <a-alert 
            :message="`系统将在 ${rebootCountdown} 秒后重启`" 
            type="info" 
            show-icon 
          />
        </div>

        <a-alert 
          v-if="resetCompleted" 
          message="出厂重置完成！" 
          type="success" 
          show-icon 
        />
        
        <a-alert 
          v-if="resetFailed" 
          message="出厂重置失败，请重试" 
          type="error" 
          show-icon 
        />
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed } from 'vue';
import { message } from 'ant-design-vue';
import request from '../../utils/request';

export default defineComponent({
  name: 'FactoryResetConfig',
  setup() {
    // 重置选项
    const resetOptions = ref(['restart_system']);
    
    // 确认对话框状态
    const confirmModalVisible = ref(false);
    const confirmText = ref('');
    
    // 重启确认对话框状态
    const restartConfirmVisible = ref(false);
    const restartDelay = ref(3);
    const isRestarting = ref(false);
    
    // 重置状态
    const resetState = reactive({
      progressVisible: false,
      isResetting: false,
      message: '正在执行出厂重置...',
      completed: false,
      failed: false
    });
    
    // 重启倒计时状态
    const rebootCountdown = ref(0);
    let countdownTimer = null;

    /**
     * 显示确认对话框
     */
    const showConfirmModal = () => {
      confirmModalVisible.value = true;
      confirmText.value = '';
    };

    /**
     * 显示重启确认对话框
     */
    const showRestartConfirmModal = () => {
      restartConfirmVisible.value = true;
      restartDelay.value = 3;
    };

    /**
     * 执行出厂重置
     */
    const performReset = async () => {
      try {
        // 关闭确认对话框，显示进度对话框
        confirmModalVisible.value = false;
        resetState.progressVisible = true;
        resetState.isResetting = true;
        resetState.message = '正在执行出厂重置...';
        resetState.completed = false;
        resetState.failed = false;

        const requestBody = {
          id: String(Date.now()),
          method: "system.factoryReset",
          params: {
            preserve_network: resetOptions.value.includes('preserve_network'),
            restart_system: resetOptions.value.includes('restart_system')
          }
        };

        const response = await request.post('/v1/jsonrpc2', requestBody);
        
        if (response.data.error) {
          throw new Error(response.data.error?.message || response.data.message || '出厂重置失败');
        }
        
        const result = response.data.result;
        resetState.message = result.message || '出厂重置完成';
        resetState.completed = true;
        
        message.success('出厂重置完成！');
        
        // 如果需要重启，调用重启API
        if (result.restart_system && result.restart_countdown) {
          startRebootCountdown(result.restart_countdown);
          // 调用重启API
          setTimeout(async () => {
            try {
              const restartRequestBody = {
                id: String(Date.now()),
                method: "system.restart",
                params: {
                  delay: 1,
                  reason: "Factory reset completed"
                }
              };
              await request.post('/v1/jsonrpc2', restartRequestBody);
            } catch (error) {
              console.warn('重启API调用失败，设备可能已经重启:', error);
            }
          }, (result.restart_countdown - 1) * 1000);
        }
        
      } catch (error) {
        console.error('出厂重置失败:', error);
        resetState.failed = true;
        resetState.message = '出厂重置失败：' + (error.message || '未知错误');
        message.error('出厂重置失败：' + (error.message || '未知错误'));
      } finally {
        resetState.isResetting = false;
      }
    };

    /**
     * 启动重启倒计时
     * @param {number} seconds - 倒计时秒数
     */
    const startRebootCountdown = (seconds) => {
      rebootCountdown.value = seconds;
      
      countdownTimer = setInterval(() => {
        rebootCountdown.value--;
        if (rebootCountdown.value <= 0) {
          clearInterval(countdownTimer);
          resetState.message = '设备正在重启，请稍候...';
          // 可以在这里添加自动刷新页面或重新连接的逻辑
          setTimeout(() => {
            window.location.reload();
          }, 2000);
        }
      }, 1000);
    };

    /**
     * 执行系统重启
     */
    const performRestart = async () => {
      try {
        isRestarting.value = true;
        restartConfirmVisible.value = false;

        const requestBody = {
          id: String(Date.now()),
          method: "system.restart",
          params: {
            delay: restartDelay.value,
            reason: "User manual restart"
          }
        };

        const response = await request.post('/v1/jsonrpc2', requestBody);
        
        if (response.data.error) {
          throw new Error(response.data.error?.message || response.data.message || '系统重启失败');
        }
        
        const result = response.data.result;
        message.success(`系统将在${result.delay_seconds}秒后重启`);
        
        // 启动倒计时显示
        if (result.delay_seconds > 0) {
          startRebootCountdown(result.delay_seconds);
          resetState.progressVisible = true;
          resetState.message = `系统将在${result.delay_seconds}秒后重启...`;
        } else {
          resetState.progressVisible = true;
          resetState.message = '系统正在重启，请稍候...';
          setTimeout(() => {
            window.location.reload();
          }, 3000);
        }
        
      } catch (error) {
        console.error('系统重启失败:', error);
        message.error('系统重启失败：' + (error.message || '未知错误'));
      } finally {
        isRestarting.value = false;
      }
    };

    return {
      resetOptions,
      confirmModalVisible,
      confirmText,
      restartConfirmVisible,
      restartDelay,
      isRestarting,
      resetProgressVisible: computed(() => resetState.progressVisible),
      isResetting: computed(() => resetState.isResetting),
      resetMessage: computed(() => resetState.message),
      resetCompleted: computed(() => resetState.completed),
      resetFailed: computed(() => resetState.failed),
      rebootCountdown,
      showConfirmModal,
      showRestartConfirmModal,
      performReset,
      performRestart
    };
  }
});
</script>

<style scoped>
.factory-reset-config {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.reset-progress {
  text-align: center;
  padding: 24px;
}

.reset-message {
  margin-top: 16px;
  font-size: 16px;
}

.reboot-countdown {
  margin-top: 16px;
}

:deep(.ant-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.ant-alert) {
  margin-bottom: 16px;
}
</style>